import React, { useEffect, useState } from 'react'
import { Toolbar } from '@antv/x6-react-components'
import FlowGraph from '../../Graph'
import { DataUri } from '@antv/x6'
// @ts-ignore
import reqwest from 'reqwest'

import {
  ClearOutlined,
  SaveOutlined,
  PrinterOutlined,
  UndoOutlined,
  RedoOutlined,
  CopyOutlined,
  ScissorOutlined,
  SnippetsOutlined,
  DownloadOutlined
} from '@ant-design/icons'
import '@antv/x6-react-components/es/toolbar/style/index.css'


const Item = Toolbar.Item
const Group = Toolbar.Group

export default function (props: any) {
  const [canUndo, setCanUndo] = useState(false)
  const [canRedo, setCanRedo] = useState(false)

  const copy = () => {
    const { graph } = FlowGraph
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.copy(cells)
    }
    return false
  }

  const cut = () => {
    const { graph } = FlowGraph
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.cut(cells)
    }
    return false
  }

  const paste = () => {
    const { graph } = FlowGraph
    if (!graph.isClipboardEmpty()) {
      const cells = graph.paste({ offset: 32 })
      graph.cleanSelection()
      graph.select(cells)
    }
    return false
  }

  useEffect(() => {
    const { graph } = FlowGraph
    const { history } = graph
    setCanUndo(history.canUndo())
    setCanRedo(history.canRedo())
    history.on('change', () => {
      setCanUndo(history.canUndo())
      setCanRedo(history.canRedo())
    })

    graph.bindKey(['meta+z', 'ctrl+z'], () => {
      if (history.canUndo()) {
        history.undo()
      }
      return false
    })
    graph.bindKey(['meta+shift+z', 'ctrl+y'], () => {
      if (history.canRedo()) {
        history.redo()
      }
      return false
    })
    graph.bindKey(['meta+d', 'ctrl+d'], () => {
      graph.clearCells()
      return false
    })
    graph.bindKey(['alt+s'], () => {
      graph.toPNG((datauri: string) => {
        DataUri.downloadDataUri(datauri, 'chart.png')
      })
      return false
    })
    graph.bindKey(['meta+p', 'ctrl+p'], () => {
      graph.printPreview()
      return false
    })
    graph.bindKey(['meta+c', 'ctrl+c'], copy)
    graph.bindKey(['meta+v', 'ctrl+v'], paste)
    graph.bindKey(['meta+x', 'ctrl+x'], cut)
    graph.bindKey(['ctrl+s'], () => {
      // let graphData = graph.toJSON()
      // console.log(JSON.stringify(graphData))
    })
  }, [])

  const handleClick = (name: string) => {
    const { graph } = FlowGraph
    switch (name) {
      case 'undo':
        graph.history.undo()
        break
      case 'redo':
        graph.history.redo()
        break
      case 'delete':
        graph.clearCells()
        break
      case 'download':
        graph.toPNG((datauri: string) => {
          DataUri.downloadDataUri(datauri, 'chart.png')
        })
        break
      case 'print':
        graph.printPreview()
        break
      case 'copy':
        copy()
        break
      case 'cut':
        cut()
        break
      case 'paste':
        paste()
        break
      case 'save':
        const { removeCellsId, pageType, dataJson } = FlowGraph;
        let edges = graph.getEdges()
        let LinkNodeFlag = false
        let LogicNodeFlag = false
        edges.map((edge) => {
          // @ts-ignore
          let sourceId = edge.source.cell
          // @ts-ignore
          let targetId = edge.target.cell
          // @ts-ignore
          let sourceNode = graph.getCellById(sourceId)
          let targetNode = graph.getCellById(targetId)
          // @ts-ignore
          let label = edge.getLabelAt(0)?.attrs.label.text
          edge.data = {}
          if (!label && sourceNode.data.type == "0" && targetNode.data.type == "2") {
            edge.data.label = "故障现象"
          } else {
            edge.data.label = label
          }
          edge.data.source = sourceId
          edge.data.target = targetId
          if (sourceNode.data.type == "3" && targetNode.data.type == "3") {
            LinkNodeFlag = true
          } else if (sourceNode.data.type != "2" && targetNode.data.type == "4") {
            LogicNodeFlag = true
          }
          edge.attr('line/stroke', FlowGraph.defaultEdgeColor)
        })
        if (LinkNodeFlag) {
          // @ts-ignore
          top.MSG.warning("警告！不允许链接节点与链接节点连接")
          return
        }
        if (LogicNodeFlag) {
          // @ts-ignore
          top.MSG.warning("警告！逻辑节点只允许由现象节点连接")
          return
        }
        let nodes = graph.getNodes();
        //循环节点，防止有些节点未点击，导致没有id的情况
        nodes.map((node) => {
          let id = node.id
          if (!node.data.id) {
            node.data.id = id
          }
        })
        let graphData = graph.toJSON()

        let resultJson: any = undefined;
        let resultContent: (any)[] = [];
        if (pageType == "1") { // 推理结果页面保存
          let cells = graphData.cells;
          // let dataCells = dataJson.cells; // 获取的总图节点数据

          // removeCellsId.forEach((removeId) => { // 删除总图中的节点和线
          //   for (let cellIndex = 0; cellIndex < dataCells.length; cellIndex++) {
          //     let cell = dataCells[cellIndex];
          //     if (cell.id == removeId) {
          //       dataCells.splice(cellIndex, 1) // 删除节点
          //       for (let edgeIndex = 0; edgeIndex < dataCells.length; edgeIndex++) { // 重新遍历一次删除连线
          //         let edge = dataCells[edgeIndex];
          //         if (edge.shape == "edge" && (edge.source.cell == removeId || edge.target.cell == removeId)) {
          //           dataCells.splice(edgeIndex, 1)
          //           edgeIndex--;
          //         }
          //       }
          //       break;
          //     }
          //   }
          // })

          cells.forEach((cell) => {
            // 保存时删除节点里面的是否正确信息
            // let newCell = JSON.parse(JSON.stringify(cell));

            // let dataCellIndex = 0
            // for (; dataCellIndex < dataCells.length; dataCellIndex++) {
            //   let dataCell = dataCells[dataCellIndex];
            //   if (dataCell.id == newCell.id) {
            //     dataCells.splice(dataCellIndex, 1, newCell) // 替换节点
            //     break;
            //   }
            // }
            // if (dataCellIndex == dataCells.length) {
            //   dataCells.push(newCell); // 添加节点
            // }
            if (cell.data && cell.data.result) {
              if (resultJson == undefined) {
                resultJson = {};
              }
              // @ts-ignore
              resultJson[cell.id] = cell.data.result;

              if (cell.data.result == "1") {
                cell.data.score++;
              }

              delete cell.data.result;
              delete cell.data.resultText;
            }
            // if (cell.shape != "edge") {
            //   resultContent.push(cell.id)
            // }
          })
          // graphData = dataJson;
        }

        // @ts-ignore
        let showId = top.DIALOG.showIds.top()
        if (showId) {
          let url = '/OMDS/api/rest/malfunction/save';
          // @ts-ignore
          let id = top.DIALOG.get(showId).state.data
          if (!pageType && typeof(id) != "string") {
            id = id.id;
          }
          if (pageType == "2") {
            // @ts-ignore
            id = top.DIALOG.get(showId).state.data.malId
          }
          let formData: any = {
            'id': id,
            'content': JSON.stringify(graphData),
          }
          if (pageType == "1") {
            url = '/OMDS/api/rest/inference/content/save'
            formData = {
              'content': JSON.stringify(graphData),
              'result': FlowGraph.inferenceResultData,
              'feedBackId': FlowGraph.inferenceDialogData ? FlowGraph.inferenceDialogData.feedBackId : "",
              'feedBack': resultJson,
              'id': FlowGraph.inferenceDialogData ? FlowGraph.inferenceDialogData.id : "",
              'malfunction_id': id.malfunction_id
            }

            if (FlowGraph.inferenceDialogData && FlowGraph.ininferenceDialogDataResultChange) {
              const { graph } = FlowGraph;
              let desnode = graph.getCellById(FlowGraph.inferenceDialogData.desnodeid); // 获取描述节点
              if (FlowGraph.inferenceDialogData && FlowGraph.inferenceDialogData.result == "1") {
                desnode.data.score++;
              }
              reqwest({
                method: 'post',
                url: "/OMDS/api/rest/inference/updateResult",
                data: {
                  data: JSON.stringify({
                    result: FlowGraph.inferenceDialogData.result,
                    'id': FlowGraph.inferenceDialogData.id
                  })
                },
                success: function (res: any) {
                  if (res.code == 200) {
                    // @ts-ignore
                    // top.MSG.success("保存成功!")
                    FlowGraph.ininferenceDialogDataResultChange = undefined;
                  } else {
                    // @ts-ignore
                    // top.MSG.error("保存失败!")
                  }
                }
              })
            }

          }

          reqwest({
            method: 'post',
            url: url,
            data: { data: JSON.stringify(formData) },
            success: function (res: any) {
              if (res.code == 200) {
                // @ts-ignore
                top.MSG.success("保存成功!")

                if (FlowGraph.pageType == "1") { // 推理结果总图保存后记录新的总图数据
                  FlowGraph.initGraphShape(false)
                  props.reloadResultTable && props.reloadResultTable(false)
                }
              } else {
                // @ts-ignore
                top.MSG.error("保存失败!")
              }
            }
          })
        }
        break
      default:
        break
    }
  }



  return (
    <div>
      <Toolbar hoverEffect={true} size="small" onClick={handleClick}>
        <Group>
          <Item
            name="delete"
            // @ts-ignore
            icon={<ClearOutlined />}
            tooltip="清除 (Cmd + D, Ctrl + D)"
          />
        </Group>
        <Group>
          <Item
            name="undo"
            tooltip="撤销 (Cmd + Z, Ctrl + Z)"
            // @ts-ignore
            icon={<UndoOutlined />}
            disabled={!canUndo}
          />
          <Item
            name="redo"
            tooltip="恢复 (Cmd + Shift + Z, Ctrl + Y)"
            // @ts-ignore
            icon={<RedoOutlined />}
            disabled={!canRedo}
          />
        </Group>
        <Group>
          <Item name="copy" tooltip="复制 (Cmd + C, Ctrl + C)"
            // @ts-ignore
            icon={<CopyOutlined />} />

          <Item name="cut" tooltip="剪切 (Cmd + X, Ctrl + X)"
            // @ts-ignore
            icon={<ScissorOutlined />} />
          <Item
            name="paste"
            tooltip="粘贴 (Cmd + V, Ctrl + V)"
            // @ts-ignore
            icon={<SnippetsOutlined />}
          />
        </Group>
        <Group>

          {
            <Item name="save"
              // @ts-ignore
              icon={<SaveOutlined />} tooltip="保存 (Ctrl + S)" />
          }
          <Item name="download"
            // @ts-ignore
            icon={<DownloadOutlined />} tooltip="下载 (Alt + S)" />
          {/*<Item
            name="print"
            // @ts-ignore
            icon={<PrinterOutlined />}
            tooltip="Print (Cmd + P, Ctrl + P)"
          />*/}
        </Group>
      </Toolbar>
    </div>
  )
}
